package cn.wolfcode.web.modules.visitinfo.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.wolfcode.web.commons.entity.ExcelExportEntityWrapper;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.PoiImportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.custinfo.service.ITbCustomerService;
import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import cn.wolfcode.web.modules.sys.service.SysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.wolfcode.web.modules.visitinfo.entity.TbVisit;
import cn.wolfcode.web.modules.visitinfo.service.ITbVisitService;


import link.ahsj.core.annotations.*;
import link.ahsj.core.entitys.ApiModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 叶师傅
 * @since 2024-06-03
 */
@Controller
@RequestMapping("visitinfo")
public class TbVisitController extends BaseController {

    @Autowired
    private ITbVisitService entityService;

    @Autowired
    private ITbCustomerService customerService;

    @Autowired
    private ITbCustLinkmanService custLinkmanService;

    @Autowired
    private SysUserService sysUserService;

    private static final String LogModule = "TbVisit";

    @GetMapping("/list.html")
    public String list() {
        return "visit/visitinfo/list";
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('visit:visitinfo:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        //拿到企业列表
        List<TbCustomer> tbCustomerList = customerService.list();
        mv.addObject("tbCustomerList",tbCustomerList);

        mv.setViewName("visit/visitinfo/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('visit:visitinfo:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("visit/visitinfo/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('visit:visitinfo:list')")
    public ResponseEntity page(LayuiPage layuiPage,String custId,String parameterName,String linkmanId) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());


        page=entityService.lambdaQuery()
                .eq(!StringUtils.isEmpty(custId),TbVisit::getCustId,custId) //所属企业
                .like(!StringUtils.isEmpty(linkmanId),TbVisit::getLinkmanId,parameterName)//联系人名字
                .page(page);
        //分页列表
        List<TbVisit> records = page.getRecords();
        for (TbVisit visit : records) {
            String custId1 = visit.getCustId();
            //通过客户id查询对象
            TbCustomer tbCustomer = customerService.getById(custId1);

            String linkmanId1 = visit.getLinkmanId();
            TbCustLinkman tbCustLinkman = custLinkmanService.getById(linkmanId1);
            if (tbCustLinkman!=null){
                //拿到联系人名字赋值
                visit.setLinkmanId(tbCustLinkman.getLinkman());
            }

            if(tbCustomer!=null){
                //拿到客户名称赋值
                visit.setCustId(tbCustomer.getCustomerName());

            }
            //显示录入人名字
            if(visit.getInputUser()!=null){
                SysUser sysUser = sysUserService.getById(visit.getInputUser());
                if (sysUser!=null){
                    visit.setInputUserName(sysUser.getUsername());
                }
            }


        }
        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('visit:visitinfo:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbVisit entity, HttpServletRequest request) {
        //录入时间  获取的是当前时间
        entity.setInputTime(LocalDateTime.now());
        //录入人
        //从session中获取到用户信息
        SysUser sysUser = (SysUser)request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);
        //赋值用户id
        entity.setInputUser(sysUser.getUserId());
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('visit:visitinfo:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbVisit entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('visit:visitinfo:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }
    @RequestMapping("/export")
    public void export(HttpServletResponse response)
            throws UnsupportedEncodingException {
        //1. 准备你需要导出的数据
        List<TbVisit> tbVisitList = entityService.list();


        //设置属性
        ExportParams exportParams=new ExportParams();
        //2. 封装成workbook
        /**
         * 参数一: 表格属性
         * 参数二: 你需要导出的实体类的字节码  需要配合@Excel注释使用
         * 参数三: 你需要导出的数据
         */
        Workbook workbook = ExcelExportUtil.exportExcel
                (exportParams,
                        TbVisit.class,
                        tbVisitList);
        //3. 导出
        /**
         * 参数一 需要一个响应
         * 参数二 文件名字
         * 参数三 工作簿
         */
        PoiExportHelper.exportExcel(response,"联系人走访管理",workbook);
    }
    /** ---------------------------**/

    @GetMapping("import.html")
    public ModelAndView toImport(ModelAndView mv) {

        mv.setViewName("visit/visitinfo/importUser");
        return mv;
    }

    @GetMapping("template")
    public void template(HttpServletResponse response) throws UnsupportedEncodingException {
        ExcelExportEntityWrapper wrapper = new ExcelExportEntityWrapper();
        wrapper.entity(TbVisit.CUSTID_COL,"custId",30);
        wrapper.entity(TbVisit.LINKMANID_COL,"linkmanId",30);


        Workbook workbook = ExcelExportUtil.exportExcel(
                new ExportParams(),
                wrapper.getResult(),
                new ArrayList<>());

        PoiExportHelper.exportExcel(response, "联系人走访管理模板", workbook);

    }


    @PostMapping("import")
    public ResponseEntity importUser(MultipartFile file) throws Exception {
        //上传的参数
        ImportParams params = PoiImportHelper.buildImportParams(
                new String[]{
                        TbVisit.CUSTID_COL,
                        TbVisit.LINKMANID_COL
                }, new Class[]{ImportGroup.class});


        //上传的结果集
        List<TbVisit> visitList = ExcelImportUtil.importExcel(
                file.getInputStream(),
                TbVisit.class, params);

        //批量保存
        entityService.saveBatch(visitList);



        return ResponseEntity.ok(ApiModel.ok());
    }

}
